using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class ChatDeepSeek : LLM
{
	private void Awake()
	{
		url = "https://api.deepseek.com/chat/completions";
		api_key = "sk-4a66891898394c04a56f4d4a25b893cc"; // ✅ 替换为你的实际密钥（以 sk- 开头）
	}

	/// <summary>
	/// api key
	/// </summary>
	[SerializeField] private string api_key;

	/// <summary>
	/// AI 设置
	/// </summary>
	public string m_SystemSetting = string.Empty;

	/// <summary>
	/// 模型名称
	/// </summary>
	public string m_ModelName = "deepseek-chat";

	private void Start()
	{
		// 初始化时添加系统设置
		m_DataList.Add(new SendData("system", m_SystemSetting));
	}

	/// <summary>
	/// 发送消息
	/// </summary>
	/// <returns></returns>
	public override void PostMsg(string _msg, Action<string> _callback)
	{
		base.PostMsg(_msg, _callback);
	}

	/// <summary>
	/// 发起请求
	/// </summary>
	/// <param name="_postWord"></param>
	/// <param name="_callback"></param>
	/// <returns></returns>
	public override IEnumerator Request(string _postWord, System.Action<string> _callback)
	{
		stopwatch.Restart();

		if (string.IsNullOrEmpty(api_key))
		{
			Debug.LogError("API Key is missing! Please set it in the inspector or constructor.");
			yield break;
		}

		using (UnityWebRequest request = new UnityWebRequest(url, "POST"))
		{
			PostData _postData = new PostData
			{
				model = m_ModelName,
				messages = m_DataList
			};

			string _jsonText = JsonUtility.ToJson(_postData);
			byte[] data = System.Text.Encoding.UTF8.GetBytes(_jsonText);
			request.uploadHandler = (UploadHandler)new UploadHandlerRaw(data);
			request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

			request.SetRequestHeader("Content-Type", "application/json");
			request.SetRequestHeader("Authorization", $"Bearer {api_key}");

			yield return request.SendWebRequest();

			if (request.responseCode == 200)
			{
				string _msgBack = request.downloadHandler.text;
				MessageBack _textback = JsonUtility.FromJson<MessageBack>(_msgBack);
				if (_textback != null && _textback.choices.Count > 0)
				{
					string _backMsg = _textback.choices[0].message.content;
					m_DataList.Add(new SendData("assistant", _backMsg));
					_callback(_backMsg);
				}
			}
			else
			{
				string _msgBack = request.downloadHandler.text;
				Debug.LogError(_msgBack);
			}

			stopwatch.Stop();
			Debug.Log("DeepSeek耗时：" + stopwatch.Elapsed.TotalSeconds);
		}
	}

	#region 数据结构

	[Serializable]
	public class PostData
	{
		public string model;
		public List<SendData> messages;
		public bool stream = false;
	}

	[Serializable]
	public class MessageBack
	{
		public string id;
		public string created;
		public string model;
		public List<MessageBody> choices;
	}

	[Serializable]
	public class MessageBody
	{
		public Message message;
		public string finish_reason;
		public string index;
	}

	[Serializable]
	public class Message
	{
		public string role;
		public string content;
	}

	#endregion
}